package org.abettor.pushbox.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import org.abettor.android.ads.YoumiManager;
import org.abettor.pushbox.activity2.ResovedMapUserList;
import org.abettor.pushbox.activity2.ShowMapDetailActivity;
import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.download.DownloadMap;
import org.abettor.pushbox.download.ParaDownloadRetValue;
import org.abettor.pushbox.map.AsyncGenerateNetMapThumbImage;
import org.abettor.pushbox.model.NetPushBoxMapBean;
import org.abettor.pushbox.model.NotifyBean;
import org.abettor.pushbox.model.SelfMessage;
import org.abettor.pushbox.R;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 网友上传的地图库
 */
public class NetUserMapActivity extends TabActivity {
	private static final int VIEW_ANSWER_RESULT = Menu.FIRST;//
	private static final int VIEW_ANSWER_LIST = Menu.FIRST + 1;// 查看解答人列表
	private static final int VIEW_DETAIL = Menu.FIRST + 2;// 查看详情
	private final float WIDTH = 70, HEIGHT = 70;
	private TabHost tabHost = null;// 标签的host
	private static final String TAB1 = "tab1", TAB2 = "tab2", TAB3 = "tab3";
	private TabHost.TabSpec netuserSpec;// 用户列表的标签
	private TabHost.TabSpec myupmapSpec;// 我上传地图的标签
	private TabHost.TabSpec myupresolveSpec;// 我上传的解决办法的列表
	private String curTab = null;// 当前的tab
	private boolean isLoading = false;// 判断当前的状态，是否处于加载状态
	private int isHasMore;// 判断是否还有更多的数据
	private Handler mHandler = new Handler();
	private DownloadMap netBeanDown = null;// 用来下载地图的bean
	private Date lastAccessTime = null;// 用来存取最后一条记录的基准时间
	private ProgressBar progressBar;// 进度条
	private ProgressBar progressBar2, progressBar3;// 两个进度条
	private ListView netUserListView;// 显示列表的控件
	private ListView myUploadListView;// 我上传列表的控件
	private ListView myResolvedListView;// 我解决的列表的控件
	private NetUserMapListAdapter netUserMapAdapter;// 网络用户的adapter
	private MyUploadMapListAdapter uploadMapAdapter;// 我上传地图的adapter
	private MyReolvedMapListAdapter resolvedMapListAdapter;// 我解决地图的adapter
	private MyOnTabChangeListener tabListener = new MyOnTabChangeListener();
	private NetMapItemClickListenner netMapItemClickListenner = new NetMapItemClickListenner();// 监听器
	private MyResolvedItemClickListenner myResolvedItemClickListenner = new MyResolvedItemClickListenner();// 监听器
	private MyUploadedItemClickListenner myUploadedItemClickListenner = new MyUploadedItemClickListenner();//
	/*-----------------------广告-------------------*/
	private final int SHOW_AD = 13579;
	private YoumiManager youmi = new YoumiManager(this);
	private Handler youmiHandle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == SHOW_AD) {
				// 按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if (val < 70) {
					youmi.showYoumi(YoumiManager.Position.bottom, Color.WHITE,
							Color.BLACK, 0xAA);
				}
			}

			super.handleMessage(msg);
		}
	};
	private Thread youmiDelayThread = new Thread() {
		@Override
		public void run() {
			try {
				Thread.sleep(200);
				Message msg = new Message();
				msg.what = SHOW_AD;
				youmiHandle.sendMessage(msg);
			} catch (InterruptedException e) {
				Log.d(this.getClass().getName(), "", e);
			}
		}
	};

	/*-----------------------------------注册context按钮----------------------------------------*/
	/**
	 * 注册context按钮
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle(R.string.net_map);
		menu.add(0, VIEW_ANSWER_RESULT, 0, R.string.net_map_do_answer);// 解答的按钮
		menu.add(0, VIEW_ANSWER_LIST, 1, R.string.net_map_answer_list);// 解答人列表
		menu.add(0, VIEW_DETAIL, 2, R.string.net_map_view_detail);//
	}

	@Override
	public boolean onContextItemSelected(MenuItem aItem) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) aItem
				.getMenuInfo();
		switch (aItem.getItemId()) {
		case VIEW_ANSWER_RESULT:// 解答的按钮
			doAnswer(info.targetView, (int) info.id);
			break;
		case VIEW_ANSWER_LIST:// 解答人列表的按钮
			doViewAnswerList((int) info.id);// 查看解决人列表的操作
			break;
		case VIEW_DETAIL:// 查看详情
			doViewDetail((int) info.id);
			break;
		}
		return false;
	}

	/*---------------------列表点击的Listenner-------------------------*/
	private class NetMapItemClickListenner implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> l, View v, int position, long id) {
			// doAnswer(v,(int)id);
			doViewDetail((int) id);// 显示详情的操作
		}
	}

	// 进行解答的操作
	private void doAnswer(View v, int id) {
		Intent in = new Intent();
		Bundle extras = new Bundle();
		extras.putInt("_id", (int) id);
		in.putExtras(extras);
		TextView hidden = (TextView) v.findViewWithTag("hidden");
		String text = hidden.getText().toString();
		if ("1".equals(text)) {// 判断是否本人已经解决
			// 本人已解决，先查寻本地答案文件是否已经存在,不存在的话，打开地图的文件，存在的话打开解答后的地图
			String filePath = Config.getNetBasePath() + File.separator
					+ String.valueOf(id) + ".step";
			File file = new File(filePath);
			if (!file.exists()) {
				in.setClass(NetUserMapActivity.this,
						NetPushBoxMapActivity.class);
			} else {
				in.setClass(NetUserMapActivity.this,
						NetBoxShowResultActivity.class);
			}
		} else {// 本人未解决的条件
			in.setClass(NetUserMapActivity.this, NetPushBoxMapActivity.class);
		}
		// NetUserMapActivity.this.finish();
		startActivity(in);
	}

	// 进行查看详情的操作
	private void doViewDetail(int id) {
		Intent in = new Intent();
		Bundle extras = new Bundle();
		extras.putInt("_id", (int) id);
		// extras.putString("class_name", "NetUserMapActivity");
		in.putExtras(extras);
		in.setClass(this, ShowMapDetailActivity.class);
		// NetUserMapActivity.this.finish();
		startActivity(in);
	}

	// 查看解决人列表的操作
	private void doViewAnswerList(int id) {
		Bundle extras = new Bundle();
		Intent intent = new Intent();
		intent.setClass(this, ResovedMapUserList.class);
		extras.putInt("_id", id);
		intent.putExtras(extras);
		this.startActivity(intent);
	}

	// 我已解决过的地图的列表
	private class MyResolvedItemClickListenner extends NetMapItemClickListenner {
	}

	// 我上传的地图的列表
	private class MyUploadedItemClickListenner extends NetMapItemClickListenner {
	}

	/*----------------------滚动条的监听器---------------------------*/
	private abstract class MyOnScrollListener implements OnScrollListener {
		private boolean linloading = false;

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// 把totalItemCount剔除掉，因为加入footer，所以剔除掉totalItemCount为1的时候
			if (totalItemCount == 1) {
				return;
			}
			if (firstVisibleItem + visibleItemCount >= totalItemCount
					&& isHasMore == ParaDownloadRetValue.HASMORE) {
				if (!linloading) {
					linloading = true;
					loadMap();// 加载数据
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							linloading = false;
						}
					}, 4000);
				}
			}
		}

		protected abstract void loadMap();//

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}
	}

	// 进行滚动的监听器
	private class NetUserMapScrollListener extends MyOnScrollListener {
		@Override
		protected void loadMap() {
			loadNetMap();
		}

	}

	// 我上传地图的滚动监听器
	private class MyUploadMapScrollListener extends MyOnScrollListener {
		@Override
		protected void loadMap() {
			SelfMessage self = Config.readSelfMessage(NetUserMapActivity.this);
			if (self != null) {
				loadMyUploadMap(self.getNickName());
			}
		}
	}

	// 我解决地图的滚动监听器
	private class MyResolvedMapScrollListener extends MyOnScrollListener {
		@Override
		protected void loadMap() {
			SelfMessage self = Config.readSelfMessage(NetUserMapActivity.this);
			if (self != null) {
				loadMyResolvedMap(self.getNickName());
			}
		}
	}

	/*---------------------滚动条的监听器end----------------------------*/

	/*------------------------各种列表的监听器--------------------------*/
	// 我上传地图的监听器
	private class MyUploadMapListAdapter extends UserMapAdapter {
		public MyUploadMapListAdapter(List<NetPushBoxMapBean> list) {
			super(list);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			final NetPushBoxMapBean item;
			synchronized (netBeanList) {
				item = netBeanList.get(position);
			}
			LayoutInflater inflater = NetUserMapActivity.this
					.getLayoutInflater();
			ViewGroup theParent = (ViewGroup) inflater.inflate(
					R.layout.net_user_map_list_upload_item, parent, false);
			TextView createTimeView = (TextView) theParent
					.findViewWithTag("createTime");
			TextView messageView = (TextView) theParent
					.findViewWithTag("message");
			TextView hidden = (TextView) theParent.findViewWithTag("hidden");
			final ImageView thumbImageView = (ImageView) theParent
					.findViewWithTag("thumbImage");
			if (item.getBitmap() != null) {
				thumbImageView.setImageBitmap(item.getBitmap());
			} else {// 图片为null的话，异步更新图片
				// 设置异步更新的图片的操作
				AsyncGenerateNetMapThumbImage.NetImageCallBack callBack = new AsyncGenerateNetMapThumbImage.NetImageCallBack() {
					@Override
					public void processImage(Bitmap bit) {
						if (bit != null) {
							thumbImageView.setImageBitmap(bit);
							item.setBitmap(bit);
						}
					}
				};
				AsyncGenerateNetMapThumbImage asyn = new AsyncGenerateNetMapThumbImage(
						WIDTH, HEIGHT, callBack, NetUserMapActivity.this) {
					@Override
					public int getNetMapId() {
						return item.getId();
					}

					@Override
					public String getMapFilePath() {
						return Config.getNetBasePath();
					}

					@Override
					public String getThumbNailPath() {
						return Config.getNetBasePath();
					}
				};
				asyn.start();
			}
			// 设置时间
			createTimeView.setText(NetUserMapActivity.this
					.getText(R.string.map_create_time)
					+ "\n"
					+ sdf.format(item.getUploadDate()));
			messageView.setText(changeMsgToStr(item));
			// 设置是否已经解决
			if (item.isMyresolved()) {
				hidden.setText("1");
			} else {
				hidden.setText("0");
			}
			return theParent;
		}

		// 把消息转换为字符串
		private String changeMsgToStr(NetPushBoxMapBean bean) {
			String ret = "";
			ret = ret
					+ NetUserMapActivity.this
							.getText(R.string.netuser_map_upor) + ":"
					+ bean.getUploader() + "\n";
			if (bean.isMyresolved()) {
				ret += NetUserMapActivity.this
						.getText(R.string.netuser_map_resolved);
			} else {
				ret += NetUserMapActivity.this
						.getText(R.string.netuser_map_unresolved);
			}
			ret += "(";
			ret += NetUserMapActivity.this.getText(R.string.netuser_map_total);
			ret += bean.getResolvedCount()
					+ NetUserMapActivity.this
							.getText(R.string.netuser_map_has_resolved) + ")";
			return ret;
		}
	}

	// 我解决地图的地图列表监听器
	private class MyReolvedMapListAdapter extends UserMapAdapter {
		public MyReolvedMapListAdapter(List<NetPushBoxMapBean> list) {
			super(list);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			final NetPushBoxMapBean item;
			synchronized (netBeanList) {
				item = netBeanList.get(position);
			}
			LayoutInflater inflater = NetUserMapActivity.this
					.getLayoutInflater();
			ViewGroup theParent = (ViewGroup) inflater.inflate(
					R.layout.net_user_map_list_resolved_item, parent, false);
			TextView createTimeView = (TextView) theParent
					.findViewWithTag("createTime");
			TextView messageView = (TextView) theParent
					.findViewWithTag("message");
			TextView hidden = (TextView) theParent.findViewWithTag("hidden");
			final ImageView thumbImageView = (ImageView) theParent
					.findViewWithTag("thumbImage");
			if (item.getBitmap() != null) {
				thumbImageView.setImageBitmap(item.getBitmap());
			} else {// 图片为null的话，异步更新图片
				// 设置异步更新的图片的操作
				AsyncGenerateNetMapThumbImage.NetImageCallBack callBack = new AsyncGenerateNetMapThumbImage.NetImageCallBack() {
					@Override
					public void processImage(Bitmap bit) {
						if (bit != null) {
							thumbImageView.setImageBitmap(bit);
							item.setBitmap(bit);
						}
					}
				};
				AsyncGenerateNetMapThumbImage asyn = new AsyncGenerateNetMapThumbImage(
						WIDTH, HEIGHT, callBack, NetUserMapActivity.this) {
					@Override
					public int getNetMapId() {
						return item.getId();
					}

					@Override
					public String getMapFilePath() {
						return Config.getNetBasePath();
					}

					@Override
					public String getThumbNailPath() {
						return Config.getNetBasePath();
					}
				};
				asyn.start();
			}
			// 设置时间
			createTimeView.setText(NetUserMapActivity.this
					.getText(R.string.map_create_time)
					+ "\n"
					+ sdf.format(item.getUploadDate()));
			messageView.setText(changeMsgToStr(item));
			// 设置是否已经解决
			if (item.isMyresolved()) {
				hidden.setText("1");
			} else {
				hidden.setText("0");
			}
			return theParent;
		}

		// 把消息转换为字符串
		private String changeMsgToStr(NetPushBoxMapBean bean) {
			String ret = "";
			ret = ret
					+ NetUserMapActivity.this
							.getText(R.string.netuser_map_upor) + ":"
					+ bean.getUploader() + "\n";
			if (bean.isMyresolved()) {
				ret += NetUserMapActivity.this
						.getText(R.string.netuser_map_resolved);
			} else {
				ret += NetUserMapActivity.this
						.getText(R.string.netuser_map_unresolved);
			}
			ret += "(";
			ret += NetUserMapActivity.this.getText(R.string.netuser_map_total);
			ret += bean.getResolvedCount()
					+ NetUserMapActivity.this
							.getText(R.string.netuser_map_has_resolved) + ")";
			return ret;
		}
	}

	// 映射数据的监听器
	private class NetUserMapListAdapter extends UserMapAdapter {
		/**
		 * 构造方法
		 * 
		 * @param list
		 */
		public NetUserMapListAdapter(List<NetPushBoxMapBean> list) {
			super(list);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			final NetPushBoxMapBean item;
			synchronized (netBeanList) {
				item = netBeanList.get(position);
			}
			LayoutInflater inflater = NetUserMapActivity.this
					.getLayoutInflater();
			ViewGroup theParent = (ViewGroup) inflater.inflate(
					R.layout.net_user_map_list_item, parent, false);
			TextView createTimeView = (TextView) theParent
					.findViewWithTag("createTime");
			TextView messageView = (TextView) theParent
					.findViewWithTag("message");
			TextView hidden = (TextView) theParent.findViewWithTag("hidden");
			final ImageView thumbImageView = (ImageView) theParent
					.findViewWithTag("thumbImage");
			if (item.getBitmap() != null) {
				thumbImageView.setImageBitmap(item.getBitmap());
			} else {// 图片为null的话，异步更新图片
				// 设置异步更新的图片的操作
				AsyncGenerateNetMapThumbImage.NetImageCallBack callBack = new AsyncGenerateNetMapThumbImage.NetImageCallBack() {
					@Override
					public void processImage(Bitmap bit) {
						if (bit != null) {
							thumbImageView.setImageBitmap(bit);
							item.setBitmap(bit);
						}
					}
				};
				AsyncGenerateNetMapThumbImage asyn = new AsyncGenerateNetMapThumbImage(
						WIDTH, HEIGHT, callBack, NetUserMapActivity.this) {
					@Override
					public int getNetMapId() {
						return item.getId();
					}

					@Override
					public String getMapFilePath() {
						return Config.getNetBasePath();
					}

					@Override
					public String getThumbNailPath() {
						return Config.getNetBasePath();
					}
				};
				asyn.start();
			}
			// 设置时间
			createTimeView.setText(NetUserMapActivity.this
					.getText(R.string.map_create_time)
					+ "\n"
					+ sdf.format(item.getUploadDate()));
			messageView.setText(changeMsgToStr(item));
			// 设置是否已经解决
			if (item.isMyresolved()) {
				hidden.setText("1");
			} else {
				hidden.setText("0");
			}
			return theParent;
		}

		// 把消息转换为字符串
		private String changeMsgToStr(NetPushBoxMapBean bean) {
			String ret = "";
			ret = ret
					+ NetUserMapActivity.this
							.getText(R.string.netuser_map_upor) + ":"
					+ bean.getUploader() + "\n";
			if (bean.isMyresolved()) {
				ret += NetUserMapActivity.this
						.getText(R.string.netuser_map_resolved);
			} else {
				ret += NetUserMapActivity.this
						.getText(R.string.netuser_map_unresolved);
			}
			ret += "(";
			ret += NetUserMapActivity.this.getText(R.string.netuser_map_total);
			ret += bean.getResolvedCount()
					+ NetUserMapActivity.this
							.getText(R.string.netuser_map_has_resolved) + ")";
			return ret;
		}
	}

	// 通用的类
	private abstract class UserMapAdapter extends BaseAdapter {
		protected List<NetPushBoxMapBean> netBeanList;

		public void clear() {
			synchronized (netBeanList) {
				netBeanList.clear();
			}
		}

		// 获得最后一次更新时间
		public Date getLastAccessTime() {
			if (netBeanList == null || netBeanList.isEmpty()) {
				return null;
			}
			int size = netBeanList.size();
			NetPushBoxMapBean bean = null;
			synchronized (netBeanList) {
				bean = netBeanList.get(size - 1);
			}
			return bean.getUploadDate();
		}

		/**
		 * 向列表中加入数据
		 * 
		 * @param toAdd
		 */
		public void addNetPushBoxMapBean(List<NetPushBoxMapBean> toAdd) {
			if (toAdd == null) {
				return;
			}
			Date lastTime = getLastAccessTime();
			Iterator<NetPushBoxMapBean> itr = toAdd.iterator();
			while (itr.hasNext()) {
				NetPushBoxMapBean n = itr.next();
				if (lastTime == null || n.getUploadDate().before(lastTime)) {
					netBeanList.add(n);
				} else {
					netBeanList.add(0, n);
				}
			}
		}

		/**
		 * 构造方法
		 * 
		 * @param list
		 */
		public UserMapAdapter(List<NetPushBoxMapBean> list) {
			this.netBeanList = list;
		}

		@Override
		public int getCount() {
			synchronized (netBeanList) {
				return netBeanList.size();
			}
		}

		@Override
		public Object getItem(int position) {
			synchronized (netBeanList) {
				return netBeanList.get(position);
			}
		}

		@Override
		public long getItemId(int position) {
			synchronized (netBeanList) {
				return netBeanList.get(position).getId();
			}
		}
	}

	/*--------------- 各种listadapter end --------------------*/
	private void resetNetUserListView() {
		netUserListView.setVisibility(View.GONE);
		netUserMapAdapter.clear();
	}

	private void resetMyUploadListView() {
		myUploadListView.setVisibility(View.GONE);
		uploadMapAdapter.clear();
	}

	private void resetMyResolvedListView() {
		myResolvedListView.setVisibility(View.GONE);
		resolvedMapListAdapter.clear();
	}

	@Override
	public void onStart() {
		// TAB1 = "tab1", TAB2 = "tab2", TAB3 = "tab3";
		super.onStart();
		int notifyId = getIntent().getIntExtra(NotifyBean.NOTIFY_TAG, -1);
		if(notifyId >= 0)
		{
			NotificationManager notiMgmt = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			notiMgmt.cancel(NotifyBean.NOTIFY_TAG, notifyId);
		}

		if (curTab.equals(TAB1)) {
			if (isLoading) {
				return;
			}
			resetNetUserListView();
			loadNetMap();
		} else if (curTab.equals(TAB2)) {
			if (isLoading) {
				return;
			}
			SelfMessage self = Config.readSelfMessage(NetUserMapActivity.this);
			resetMyUploadListView();
			loadMyUploadMap(self.getNickName());
		} else if (curTab.equals(TAB3)) {
			if (isLoading) {
				return;
			}
			SelfMessage self = Config.readSelfMessage(NetUserMapActivity.this);
			resetMyResolvedListView();
			loadMyResolvedMap(self.getNickName());
		}
	}

	// 加入监听TabHost的listener
	private class MyOnTabChangeListener implements OnTabChangeListener {
		private boolean netLoaded = false;// 是否第一次启动
		private boolean myUpLoaded = false;// 上传的地图是否第一次启动
		private boolean myResolvedLoaded = false;// 我解决的地图是否第一次启动

		@Override
		public void onTabChanged(String tabId) {
			// 正在加载时，不允许切换到别的tag
			if (isLoading) {
				tabHost.setCurrentTabByTag(curTab);
				return;
			} else {
				curTab = tabId;
			}
			if (TAB1.equals(tabId)) {// tab1的标签
				// 加载网络资源的操作
				if (!netLoaded) {
					// 加载过后将不在触发加载事件
					loadNetMap();
					netLoaded = true;
				}
			} else if (TAB2.equals(tabId)) {// tab2的标签
				// 加载我上传的资源的操作
				SelfMessage self = Config
						.readSelfMessage(NetUserMapActivity.this);
				if (self == null) {
					doUnreg();
					return;
				} else {
					if (!myUpLoaded) {
						loadMyUploadMap(self.getNickName());
						myUpLoaded = true;
					}
				}
			} else if (TAB3.equals(tabId)) {// tab3的标签
				// 加载我解答过的资源的现状
				SelfMessage self = Config
						.readSelfMessage(NetUserMapActivity.this);
				if (self == null) {
					doUnreg();
					return;
				} else {
					if (!myResolvedLoaded) {
						loadMyResolvedMap(self.getNickName());
						myResolvedLoaded = true;
					}
				}
			}
		}
	}

	// 进行没有输入用户名的操作
	private void doUnreg() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog alert = builder.create();
		alert.setTitle(R.string.info);
		alert.setMessage(NetUserMapActivity.this
				.getText(R.string.netuser_map_unreginfo));
		alert.setButton(DialogInterface.BUTTON_POSITIVE,
				this.getText(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent();
						intent.setClass(NetUserMapActivity.this,
								OptionActivity.class);
						Bundle extras = new Bundle();
						extras.putString("class_name", "NetUserMapActivity");
						intent.putExtras(extras);
						NetUserMapActivity.this.startActivity(intent);
						NetUserMapActivity.this.finish();
					}
				});
		alert.setButton(DialogInterface.BUTTON_NEGATIVE,
				this.getText(android.R.string.cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		alert.show();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.net_user_map_activity);
		init();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	private void init() {
		netUserMapAdapter = new NetUserMapListAdapter(
				new LinkedList<NetPushBoxMapBean>());
		uploadMapAdapter = new MyUploadMapListAdapter(
				new LinkedList<NetPushBoxMapBean>());
		resolvedMapListAdapter = new MyReolvedMapListAdapter(
				new LinkedList<NetPushBoxMapBean>());
		// 进行初始化uploadmap的操作
		netBeanDown = new DownloadMap(this);
		tabHost = getTabHost();
		tabHost.setOnTabChangedListener(tabListener);
		LayoutInflater.from(this).inflate(R.layout.net_user_map_tabhost,
				tabHost.getTabContentView(), true);
		netuserSpec = tabHost.newTabSpec(TAB1);
		myupmapSpec = tabHost.newTabSpec(TAB2);
		myupresolveSpec = tabHost.newTabSpec(TAB3);
		setIndicator(netuserSpec, R.string.netuser_maplist);
		setIndicator(myupmapSpec, R.string.netuser_mymaplist);
		setIndicator(myupresolveSpec, R.string.netuser_mysolved);
		netuserSpec.setContent(R.id.view1);
		myupmapSpec.setContent(R.id.view2);
		myupresolveSpec.setContent(R.id.view3);
		tabHost.addTab(netuserSpec);
		tabHost.addTab(myupmapSpec);
		tabHost.addTab(myupresolveSpec);
		// 设置当前的tag
		curTab = TAB1;
		// 获得list的控件
		netUserListView = (ListView) this.findViewById(R.id.netUserList);
		myUploadListView = (ListView) this.findViewById(R.id.myUploadList);
		myResolvedListView = (ListView) this.findViewById(R.id.myResolvedList);
		addFooterView(netUserListView);
		addFooterView(myUploadListView);
		addFooterView(myResolvedListView);
		netUserListView.setAdapter(netUserMapAdapter);
		netUserListView.setOnItemClickListener(netMapItemClickListenner);
		myUploadListView.setAdapter(uploadMapAdapter);
		myUploadListView.setOnItemClickListener(myUploadedItemClickListenner);
		myResolvedListView.setAdapter(resolvedMapListAdapter);
		myResolvedListView.setOnItemClickListener(myResolvedItemClickListenner);
		// 注册context menu的操作
		registerForContextMenu(netUserListView);
		registerForContextMenu(myUploadListView);
		registerForContextMenu(myResolvedListView);
		// 加入滚动的监听器;
		netUserListView.setOnScrollListener(new NetUserMapScrollListener());
		myUploadListView.setOnScrollListener(new MyUploadMapScrollListener());
		myResolvedListView
				.setOnScrollListener(new MyResolvedMapScrollListener());
		youmiDelayThread.start();
	}

	// 增加footer view
	private void addFooterView(ListView listView) {
		View localView = LayoutInflater.from(this).inflate(
				R.layout.net_user_map_list_footer, null);
		listView.addFooterView(localView);
	}

	// 设置文字的颜色
	private void setIndicator(TabHost.TabSpec spec, int title) {
		View localView = LayoutInflater.from(this).inflate(
				R.layout.net_user_map_tab, null);
		TextView localTextView = (TextView) localView
				.findViewById(R.id.net_user_tab_text);
		localTextView.setText(title);
		spec.setIndicator(localView);
	}

	// 加载网络资源
	private void loadNetMap() {
		// 已经在加载时就不在加载
		if (isLoading) {
			return;
		}
		Thread thread = new Thread() {
			@Override
			public void run() {
				loadNetMapOperation();
			}
		};
		curTab = TAB1;
		isLoading = true;// 把状态设为加载中
		showProgressBar();// 显示加载中的progressbar
		thread.start();
	}

	// 加载我上传地图列表
	private void loadMyUploadMap(final String nickName) {
		// 已经在加载时地图就不在加载
		if (isLoading) {
			return;
		}
		Thread thread = new Thread() {
			@Override
			public void run() {
				loadUploadNetMapOperation(nickName);
			}
		};
		curTab = TAB2;
		isLoading = true;
		showMyUploadProgressBar();// 显示加载中的progressbar
		thread.start();
	}

	// 加载我解决地图的列表
	private void loadMyResolvedMap(final String nickName) {
		// 已经加载时地图就不在加载
		if (isLoading) {
			return;
		}
		Thread thread = new Thread() {
			@Override
			public void run() {
				loadMyResolvedMapOperation(nickName);
			}
		};
		curTab = TAB3;
		isLoading = true;
		showMyResolvedProgressBar();// 显示加载中的progressbar
		thread.start();
	}

	// 加载我解决了的地图的列表
	private void loadMyResolvedMapOperation(String nickName) {
		lastAccessTime = resolvedMapListAdapter.getLastAccessTime();
		String content = netBeanDown.downloadResolvedMapListStr(nickName,
				lastAccessTime, Config.PAGESIZE);
		dispearMyResolvedProgressBar();// 使加载框消失
		isLoading = false;
		// 读取内容为空，显示加载失败的对话框
		if (content == null) {
			loadResolvedMapFailure(nickName);// 显示加载失败的对话框
			return;
		}
		// 判断是否还有更多的数据
		isHasMore = ParaDownloadRetValue.isHasMoreNetMap(content);
		if (isHasMore == ParaDownloadRetValue.ERROR) {
			loadResolvedMapFailure(nickName);// 显示加载失败的对话框
			return;
		}
		// 解析数据的列表
		final List<NetPushBoxMapBean> retList = ParaDownloadRetValue
				.paraNetMap(content);
		if (retList == null) {
			loadResolvedMapFailure(nickName);// 显示加载失败的对话框
			return;
		}
		// 显示加载后的列表框
		showResolvedView();// 显示用户的对话框
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				Log.d(this.getClass().getName(), "size: " + retList.size());
				resolvedMapListAdapter.addNetPushBoxMapBean(retList);
				resolvedMapListAdapter.notifyDataSetChanged();
			}
		});
	}

	// 加载我上传的网络地图的操作
	private void loadUploadNetMapOperation(String nickName) {
		lastAccessTime = uploadMapAdapter.getLastAccessTime();
		String content = netBeanDown.downloadMapListStr(nickName,
				lastAccessTime, nickName, Config.PAGESIZE);
		dispearMyUploadProgressBar();// 使加载框消失
		isLoading = false;
		// 读取内容为空，显示加载失败的对话框
		if (content == null) {
			loadUploadNetMapFailure(nickName);// 显示加载失败的对话框
			return;
		}
		// 判断是否还有更多的数据
		isHasMore = ParaDownloadRetValue.isHasMoreNetMap(content);
		// 解析数据内容失败，显示加载失败的对话框
		if (isHasMore == ParaDownloadRetValue.ERROR) {
			loadUploadNetMapFailure(nickName);// 显示加载失败的对话框
			return;
		}
		// 解析数据的列表
		final List<NetPushBoxMapBean> retList = ParaDownloadRetValue
				.paraNetMap(content);
		if (retList == null) {
			loadUploadNetMapFailure(nickName);// 显示加载失败的对话框
			return;
		}
		// 显示加载后的列表框
		showUploadMapView();// 显示用户的对话框
		Log.d(this.getClass().getName(), "size: " + retList.size());
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				uploadMapAdapter.addNetPushBoxMapBean(retList);
				uploadMapAdapter.notifyDataSetChanged();
			}
		});
	}

	// loadNetMap operation
	private void loadNetMapOperation() {
		lastAccessTime = netUserMapAdapter.getLastAccessTime();// 获得最近存取的时间
		SelfMessage self = Config.readSelfMessage(NetUserMapActivity.this);
		String myNickName = null;
		if (self == null) {
			myNickName = null;
		} else {
			myNickName = self.getNickName();
		}
		String content = netBeanDown.downloadMapListStr(null, lastAccessTime,
				myNickName, Config.PAGESIZE);
		dispearProgressBar();// 使加载框消失
		isLoading = false;
		// 读取内容为空，显示加载失败的对话框
		if (content == null) {
			loadNetMapFailure();// 显示加载失败的对话框
			return;
		}
		// 判断是否还有更多的数据
		isHasMore = ParaDownloadRetValue.isHasMoreNetMap(content);
		// 解析数据内容失败，显示加载失败的对话框
		if (isHasMore == ParaDownloadRetValue.ERROR) {
			loadNetMapFailure();// 显示加载失败的对话框
			return;
		}
		// 解析数据的列表
		final List<NetPushBoxMapBean> retList = ParaDownloadRetValue
				.paraNetMap(content);
		if (retList == null) {
			loadNetMapFailure();// 显示加载失败的对话框
			return;
		}
		// 显示加载后的列表框
		showNetUserMapView();// 显示用户的对话框
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				netUserMapAdapter.addNetPushBoxMapBean(retList);
				netUserMapAdapter.notifyDataSetChanged();
			}
		});
	}

	// dispear progressBar
	private void dispearProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				int state = netUserListView.getVisibility();
				if (state == View.GONE) {// 大对话框，消失的操作
					progressBar = (ProgressBar) NetUserMapActivity.this
							.findViewById(R.id.progressBar1);
					progressBar.setVisibility(View.GONE);
				} else {// 小对话框的消失操作
					View view = netUserListView.findViewById(R.id.footor);
					view.setVisibility(View.GONE);
				}
			}
		});
	}

	// 使上传对话框消失的操作
	private void dispearMyUploadProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				int state = myUploadListView.getVisibility();
				if (state == View.GONE) {
					progressBar2 = (ProgressBar) NetUserMapActivity.this
							.findViewById(R.id.progressBar2);
					progressBar2.setVisibility(View.GONE);
				} else {
					View view = myUploadListView.findViewById(R.id.footor);
					view.setVisibility(View.GONE);
				}
			}
		});
	}

	// 使解决对话框消失的操作
	private void dispearMyResolvedProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				int state = myResolvedListView.getVisibility();
				if (state == View.GONE) {
					progressBar3 = (ProgressBar) NetUserMapActivity.this
							.findViewById(R.id.progressBar3);
					progressBar3.setVisibility(View.GONE);
				} else {
					View view = myResolvedListView.findViewById(R.id.footor);
					view.setVisibility(View.GONE);
				}
			}

		});
	}

	// show progressBar
	private void showProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				// 当列表框还没显示时显示大的加载框，当显示时显示列表中小的对话框
				int state = netUserListView.getVisibility();
				if (state == View.GONE) {
					progressBar = (ProgressBar) NetUserMapActivity.this
							.findViewById(R.id.progressBar1);
					progressBar.setVisibility(View.VISIBLE);
				} else {
					View view = netUserListView.findViewById(R.id.footor);
					view.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	// 显示我上传地图时的progress
	private void showMyUploadProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				// 当列表框还没显示时显示大的加载框，当显示时显示列表中小的对话框
				int state = myUploadListView.getVisibility();
				if (state == View.GONE) {
					progressBar2 = (ProgressBar) NetUserMapActivity.this
							.findViewById(R.id.progressBar2);
					progressBar2.setVisibility(View.VISIBLE);
				} else {
					View view = myUploadListView.findViewById(R.id.footor);
					view.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	// 显示我解决地图时的progress
	private void showMyResolvedProgressBar() {
		mHandler.post(new Runnable() {
			// 当列表框还没显示时，显示大对话框
			@Override
			public void run() {
				int state = myResolvedListView.getVisibility();
				if (state == View.GONE) {
					progressBar3 = (ProgressBar) NetUserMapActivity.this
							.findViewById(R.id.progressBar3);
					progressBar3.setVisibility(View.VISIBLE);
				} else {
					View view = myResolvedListView.findViewById(R.id.footor);
					view.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	// show List View
	private void showNetUserMapView() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if (netUserListView.getVisibility() == View.GONE) {
					netUserListView.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	// show uplist view
	private void showUploadMapView() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if (myUploadListView.getVisibility() == View.GONE) {
					myUploadListView.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	// show resovled view
	private void showResolvedView() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if (myResolvedListView.getVisibility() == View.GONE) {
					myResolvedListView.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	// 加载我上传地图错误的对话框
	private void loadUploadNetMapFailure(final String nickName) {
		mHandler.post(new LoadFailureRunnable() {
			@Override
			public void loadMap() {
				loadMyUploadMap(nickName);
			}
		});
	}

	// 加载我解决地图错误的对话框
	private void loadResolvedMapFailure(final String nickName) {
		mHandler.post(new LoadFailureRunnable() {
			@Override
			public void loadMap() {
				loadMyResolvedMapOperation(nickName);
			}
		});
	}

	/**
	 * 进行加载失败处理的类
	 * 
	 * @author jzh
	 * 
	 */
	private abstract class LoadFailureRunnable implements Runnable {
		@Override
		public void run() {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					NetUserMapActivity.this);
			AlertDialog alert = builder.create();
			alert.setTitle(R.string.error);
			alert.setMessage(NetUserMapActivity.this
					.getText(R.string.netuser_loadmap_failure));
			alert.setButton(DialogInterface.BUTTON_POSITIVE,
					NetUserMapActivity.this.getText(R.string.netuser_retry),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 显示加载的对话标签
							showProgressBar();
							// 重新网络地图的操作
							loadMap();
						}
					});
			alert.setButton(DialogInterface.BUTTON_NEGATIVE,
					NetUserMapActivity.this.getText(android.R.string.cancel),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			alert.show();
		}

		public abstract void loadMap();
	}

	// 显示加载网络地图错误的的对话狂
	private void loadNetMapFailure() {
		mHandler.post(new LoadFailureRunnable() {
			@Override
			public void loadMap() {
				loadNetMap();
			}
		});
	}
}
